from bluedot.settings import POLVY_APPID, POLVY_USERID, POLVY_APPSECRET
import json, hashlib, requests, time

def getSign(params):
    sign = POLVY_APPSECRET

    for k in sorted(params):
        sign = sign + k + params[k]

    sign = sign + POLVY_APPSECRET

    return md5_encrypt(sign).upper()


def createLive(name, passwd, scene, max_viewer, start_time, publisher):
    timestamp = int(round(time.time()))

    params = {
        "appId": POLVY_APPID,
        "autoPlay": 1,
        "name": name,
        "timestamp": timestamp,
        "userId": POLVY_USERID,
        "channelPasswd": passwd
    }

    params["sign"] = getSign(params)

    resp = requests.post("http://api.polyv.net/live/web/v1/channels", data=params).json()
    if resp.get("status") != "success":
        raise Exception("创建直播失败")

    return resp.get('result')


def md5_encrypt(content):
    md5 = hashlib.md5()
    md5.update(content.encode())
    return md5.hexdigest()


